﻿using PetaPoco;
using System.Runtime.CompilerServices;

namespace BlazorAdmin.Extensions
{
    /// <summary>
    /// 数字转枚举转换器
    /// </summary>
    public class NumberToEnumConverter : ValueConverterAttribute
    {
        /// <summary>
        /// 获得/设置 目标类型
        /// </summary>
        protected Type TargetType { get; }

        public NumberToEnumConverter(Type targetType) => TargetType = targetType;

        public override object? ConvertFromDb(object? value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            if (value != null && Enum.TryParse(TargetType, value!.ToString(), ignoreCase: true, out object? result))
            {
                return result;
            }

            DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new(10, 2);
            if (null != value)
                defaultInterpolatedStringHandler.AppendFormatted(value);
            defaultInterpolatedStringHandler.AppendLiteral(" 无法转化为 ");
            defaultInterpolatedStringHandler.AppendFormatted(TargetType.Name);
            defaultInterpolatedStringHandler.AppendLiteral(" 成员");
            throw new InvalidCastException(defaultInterpolatedStringHandler.ToStringAndClear());
        }

        public override object? ConvertToDb(object? value)
        {
            string? text = value?.ToString();
            if (!string.IsNullOrEmpty(text) && Enum.TryParse(TargetType, text, out object? result))
            {
                return result;
            }

            throw new InvalidCastException(TargetType.Name + " 未定义 " + text + " 成员");
        }
    }
}
